﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Web.Services;
using System.Web.Services.Description;
using System.Xml.Serialization;
using Galaktika.BI.Silverlight.Services;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.DataAccess;

namespace Galaktika.BI.Silverlight.ClientApp.Web
{
    [XmlRoot(Namespace = Common.Namespace)]
    [DataContract(Namespace = Common.Namespace)]
    public class ScoresResult
    {     
        public ScoresResult()
        {
        }

        public ScoresResult(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            this.Name = name;
        }

        public ScoresResult(string name, string score)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (string.IsNullOrEmpty(score))
            {
                throw new ArgumentNullException("score");
            }

            this.Name = name;
            this.Score = score;
        }

        public ScoresResult(string name, string score, string code)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (string.IsNullOrEmpty(score))
            {
                throw new ArgumentNullException("score");
            }
            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentNullException("code");
            }

            this.Name = name;
            this.Score = score;
            this.Code = code;
        }

        [XmlElement(IsNullable = true)]
        [DataMember]
        public string Width { get; set; }

        [XmlElement(IsNullable = true)]
        [DataMember]
        public string Height { get; set; }

        [XmlElement(IsNullable = true)]
        [DataMember]
        public string Colors { get; set; }

        [XmlElement]
        [DataMember]
        public string Score { get; set; }

        [XmlElement(IsNullable = true)]
        [DataMember]
        public string Date { get; set; }

        [XmlElement(IsNullable = true)]
        [DataMember]
        public string Time { get; set; }

        [XmlElement]
        [DataMember]
        public string Code { get; set; }

        [XmlElement]
        [DataMember]
        public string Name { get; set; }
    }

    [WebService(Namespace = Common.Namespace)]
    public interface IScores
    {
        // Methods
        //[OperationContract(AsyncPattern = true, Action = "http://tempuri.org/IScores/AddScore", ReplyAction = "http://tempuri.org/IScores/AddScoreResponse")]
        void AddScore(string width, string height, string colors, string score, string date, string time, string code, string name);
        //void EndAddScore(IAsyncResult result);
    }

    public class Scores : WebService,IScores
    {
        // Fields
        //private SendOrPostCallback onAddScoreCompletedDelegate;
        private static List<ScoresResult> items;
        //private static Dictionary<int, Dictionary<string, string>> orderedItems;
        
        static Scores()
        {
            items = new List<ScoresResult>();
            //orderedItems = new Dictionary<int, Dictionary<string, string>>();
        }

        //[WebMethod(EnableSession = true)]
        //private void AddScore(int width, int height, int colors, int score, int date, int time, int code, int name)
        //{
           
        //}

        [WebMethod(EnableSession = true)]
        //[System.ServiceModel.FaultContract(typeof(ApplicationException))]
        public InvokeResultSchema InvokeCommand(InvokeSchema invoker)
        {
            InvokeResultSchema res = null;
            try
            {
                var connectionString = invoker[KnownInvokeArgs.ConnectionString];
                var query = invoker[KnownInvokeArgs.Query];
                var sessionId = invoker[KnownInvokeArgs.SessionId];
                var connectionType = invoker[KnownInvokeArgs.ConnectionType];

                res = QueryExecutorFactory.Create(connectionType).ExecuteQuery(connectionString, query, sessionId);
            }
            catch (Exception exc)
            {
                res = new InvokeResultSchema(invoker.CommandId, exc.ToString(), KnownContentTypes.Error);
            }

            return res;
        }

        [WebMethod(EnableSession = true)]
        public List<ScoresResult> GetTop5()
        {
            var result = new List<ScoresResult>();
            int i = 0;
            var ordered = from x in items
                          orderby Convert.ToInt32(x.Score)
                          descending 
                          select x;            
            foreach (var order in ordered)
            {
                if (i < 5)
                {
                    var item = new ScoresResult(order.Name, order.Score);
                    result.Add(item);
                    i++;
                }
                else
                    break;                
            }                
            return result;
        }
        #region IScores Members

        [WebMethod(EnableSession = true)]
        public void AddScore(string width, string height, string colors, string score, string date, string time, string code, string name)
        {
            var item = new ScoresResult();
            item.Width = width;
            item.Height = height;
            item.Colors = colors;
            item.Score = score;
            item.Date = date;
            item.Date = time;
            item.Code = code;
            item.Name = name;
            items.Add(item);
              
        }

        #endregion
    }

    //[ServiceContract(
    //    Namespace = Galaktika.BI.Silverlight.Common.Namespace)]
    //[ServiceBehavior(
    //    ConcurrencyMode = ConcurrencyMode.Multiple,
    //    InstanceContextMode = InstanceContextMode.Single)]
    //[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    //public class Scores
    //{


    //    [OperationContract]
    //    public InvokeResultSchema InvokeCommand(InvokeSchema invoker)
    //    {
    //        InvokeResultSchema res = null;
    //        try
    //        {
    //            res = CommandDispatcher.Dispatch(invoker).Invoke();
    //        }
    //        catch (Exception exc)
    //        {
    //            res = new InvokeResultSchema(invoker.CommandId, exc.ToString(), KnownContentTypes.Error);
    //        }

    //        return res;
    //    }

    //    // Add more operations here and mark them with [OperationContract]
    //}
}
